#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
运行指定的 show_message_flow.json 流程，并校验 Redis 键对应的值是否存在并打印出来。
"""
import json
import os
import sys

# 确保项目根目录在 sys.path 中
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from flow_engine.core.graph import FlowGraph
from flow_engine.execution.runner import FlowRunner
from api.managers.redis_manager import REDIS_MANAGER


def load_flow_from_path(path: str) -> dict:
    # 兼容 UTF-8 BOM
    with open(path, 'rb') as fb:
        raw = fb.read()
    text = raw.decode('utf-8-sig', errors='replace').lstrip('\ufeff')
    return json.loads(text)


def main():
    # 指定流程文件路径
    flow_path = r"e:\\work\\work_ai\\flow-engine\\examples\\show_message_flow.json"
    print(f"加载流程文件: {flow_path}")
    flow = load_flow_from_path(flow_path)
    graph = FlowGraph(flow)

    # 构造初始上下文（参考 run_flow.py）
    context = {
        'user': {
            'role': 'guest',
            'name': 'Alice',
        },
        'request': {
            'query': 'hello world',
        },
        'event': {
            'eventId': 'REGISTER_ACCOUNT',
            'eventName': 'Partner Registered',
            'eventSource': 'fuse pro',
            'data': {
                'email': 'alice@example.com'
            }
        }
    }

    # 运行流程（需要提供有效的 flow_id 以创建 runId）
    runner = FlowRunner(graph, max_steps=1000, flow_id=999)
    result = runner.run(context)

    run_id = runner._run_id
    key = f"{run_id}_context"
    print(f"\n运行完成，runId={run_id}")
    print(f"Redis 键: {key}")

    value = REDIS_MANAGER.get_json(key)
    exists = value is not None
    print(f"存在: {exists}")
    print("值:")
    print(json.dumps(value, ensure_ascii=False, indent=2) if value is not None else "null")

    # 同时打印内存中的最终上下文 flow 元数据以交叉验证
    try:
        flow_meta = result['context'].get('flow', {})
        print("\n上下文中的 flow 元数据:")
        print(json.dumps(flow_meta, ensure_ascii=False, indent=2))
    except Exception:
        pass


if __name__ == '__main__':
    main()